import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:wallpaper/api/mobile.dart';
import 'package:wallpaper/components/images/image_list.dart';
import 'package:wallpaper/model/image_base.dart';

// ignore: must_be_immutable
class MobileHome extends StatefulWidget {
  String order;
  final void Function()? onScrollStart;
  final void Function()? onScrollEnd;
  MobileHome({
    super.key,
    required this.order,
    this.onScrollStart,
    this.onScrollEnd,
  });

  @override
  State<MobileHome> createState() => _MobilePageState();
}

class _MobilePageState extends State<MobileHome>
    with AutomaticKeepAliveClientMixin {
  final List<ImageBase> imgs = [];
  int page = 1;
  int limit = 30;
  bool isLoading = false;

  Future<void> getData() async {
    if (isLoading || !mounted) return;
    setState(() {
      isLoading = true;
    });

    try {
      Response res =
          await mobileAll(page: page, limit: limit, order: widget.order);
      if (res.data['msg'] == 'success') {
        setState(() {
          if (res.data['res'] == null) return;
          var data = res.data['res']['vertical'];
          List imgList = (data as List<dynamic>).map((item) {
            String largePath = item['preview'] ?? '';
            String smallPath = item['img'] ?? '';
            String tags = (item['tag'] as List<dynamic>?)?.join(' ') ?? '';
            return ImageBase(
              largePath: largePath,
              smallPath: smallPath,
              tags: tags,
            );
          }).toList();
          imgs.addAll(imgList as Iterable<ImageBase>);
          page++;
        });
      }
    } catch (e) {
      print(e);
    } finally {
      setState(() {
        isLoading = false;
      });
    }
  }

  @override
  void initState() {
    super.initState();
    // 初始化时获取数据 等待页面渲染完成
    WidgetsBinding.instance.addPostFrameCallback((_) {
      getData();
    });
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      body: ImageList(
        imageList: imgs,
        isLoading: isLoading,
        onScrollStart: widget.onScrollStart,
        onScrollEnd: widget.onScrollEnd,
        isMobile: true,
        emptyHeight: widget.order == 'new' ? 75 : 20,
        onImageBottomLoading: () {
          if (isLoading) return;
          getData();
        },
        onImageListRefresh: () {
          setState(() {
            imgs.clear();
            page = 1;
          });
          getData();
        },
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}
